import { defineReactive } from './defineReactive.mjs'
import { Dep } from './dep.mjs';
import arrayMethod from './arrayMethod.mjs';

export function observe(obj) {
    if (typeof obj !== 'object' || obj === null) {
        return;
    }
    let ob = obj.__ob__;
    if (!ob) {
        ob = new Observe(obj)
    }
    return ob;
}

class Observe {
    constructor(obj) {
        Object.defineProperty(obj, '__ob__', {
            enumerable: false,
            configurable: true,
            writable: true,
            value: this,
        })
        this.dep = new Dep();
        if (Array.isArray(obj)) {
            this.observeArray(obj)
        } else {
            this.walk(obj);
        }
    }
    walk(obj) {
        for (const key in obj) {
            defineReactive(obj, key, obj[key])
        }
    }
    observeArray(arr) {
        Object.setPrototypeOf(arr, arrayMethod);
        for (let item of arr) {
            observe(item);
        }
    }
}